package org.budo.filestore.aliyun.oss;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import org.budo.filestore.api.DeleteResponse;
import org.budo.filestore.api.DownloadRequest;
import org.budo.filestore.api.UploadRequest;
import org.budo.filestore.api.UploadResponse;
import org.budo.filestore.impl.DefaultDeleteResponse;
import org.budo.filestore.impl.DefaultUploadResponse;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class AliyunOssFileStore extends AbstractAliyunOssFileStore {
    @Override
    public String downloadUrl(DownloadRequest request) {
        Date expiration = new Date(System.currentTimeMillis() + 60 * 60 * 1000);

        OSSClient ossClient = this.getOssClient();
        URL url = ossClient.generatePresignedUrl(this.getBucketName(), request.getContentUrl(), expiration);
        return url.toString();
    }

    @Override
    public InputStream downloadStream(DownloadRequest request) {
        if (!this.getOssClient().doesObjectExist(this.getBucketName(), request.getContentUrl())) {
            return null;
        }

        OSSObject ossObject = this.getOssClient().getObject(this.getBucketName(), request.getContentUrl());
        return ossObject.getObjectContent();
    }

    @Override
    public UploadResponse upload(UploadRequest request) {
        log.info("#32 upload, request=" + request);

        PutObjectResult result = this.getOssClient().putObject(this.getBucketName(), //
                request.getContentUrl(), //
                request.getInputStream());

        ResponseMessage response = result.getResponse();
        if (null == response) {
            log.warn("#40 putObject response null, result=" + result);
            return new DefaultUploadResponse(false);
        }

        log.debug("#44 upload, request=" + request + ", response=" + response + ", result=" + result);
        boolean successful = response.isSuccessful();
        return new DefaultUploadResponse(successful);
    }

    @Override
    public DeleteResponse delete(DownloadRequest request) {
        try {
            this.getOssClient().deleteObject(this.getBucketName(), request.getContentUrl());
            return new DefaultDeleteResponse(true);
        } catch (Throwable e) {
            log.error("#46 delete error, e=" + e, e);
            return new DefaultDeleteResponse(false);
        }
    }
}